<template>
<!-- -->
<!-- <el-form ref="productFormRef" :model="productForm" :rules="productFormRules" label-width="80px">
</el-form>   -->
<!-- class="el-form--inline"    show-file-list -->
<div >
    <el-upload
        class="upload-product-picture"
        :action="uploadPictureUrl"
        :headers="headers"
        name="file"
        accept="image/png, image/jpeg, image/gif"
        ref="pictureUploader"

        :on-preview="handlePreview"
        :on-remove="handleRemove"
        :file-list="pictureList"

        :on-success="onUploadSuccess"
        :before-upload="beforeUpload"

        list-type="picture">
        <el-button size="small" type="primary">点击上传</el-button>
        <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
<!-- slot-scope="{file: picture}" -->
        <div slot="file" slot-scope="{file: picture}" ref="pictureItem">
            <img class="el-upload-list__item-thumbnail" :src="picture.url" alt="">
            <!-- el-upload-list__item-actions -->
            <span class="el-upload-list__item-actions">
                <!-- <span  class="el-upload-list__item-preview"  @click="handlePictureCardPreview(file)"><i class="el-icon-zoom-in"></i></span>
                <span  v-if="!disabled"  class="el-upload-list__item-delete"  @click="handleDownload(file)"><i class="el-icon-download"></i></span>
                <span  v-if="!disabled"  class="el-upload-list__item-delete"  @click="handleRemove(file)"><i class="el-icon-delete"></i></span> -->

                <el-button type="primary" icon="el-icon-top" size="mini" plain @click="handleMoveUp(picture)">上移</el-button>
                <el-button type="success" icon="el-icon-bottom" size="mini" plain @click="handleMoveDown(picture)">下移</el-button>
              
                <el-button type="warning" icon="el-icon-star-off" size="mini" @click="handleCover(picture)">封面</el-button>
                <el-button type="danger" icon="el-icon-delete" circle @click="handleRemove(picture)"></el-button>

<!-- class="el-upload-list__item-delete"  @click="handleRemove(picture)" -->
                <!-- <el-button type="primary" icon="el-icon-top">上移</el-button> 
                <el-button type="primary" icon="el-icon-bottom">下移</el-button>
                <el-button type="primary" icon="el-icon-search">搜索</el-button>
                <el-button type="primary">上传<i class="el-icon-upload el-icon--right"></i></el-button> -->
            </span>
        </div>


    </el-upload>

</div>
</template>
<script>
import { getToken } from "@/utils/auth"
import { addPicture, updatePictures, 
    getProductPictures, deleteProductPicture } from "@/api/catalog/product";

export default {
    name: 'ProductPicture',
    props:{
        model: Object,
        rules: Object
    },
    data () {
        return {
            pictureType: 1,
            disabled: false,
            headers: {
                Authorization: "Bearer " + getToken(),
            },
            pictureList: [],
            // 为了解决闪动问题，又加了一个 pictureList的clone数组
            pictureListModel:[]
        }
    },
    computed: {
        uploadPictureUrl () {
            return this.pictureType 
            ? (process.env.VUE_APP_BASE_API + "/common/upload/" + this.pictureType)
            : (process.env.VUE_APP_BASE_API + "/common/upload")
        },
        maxDisplayOrder () {
            if(!this.pictureList)
                return 0;
            if(!this.pictureList.length)
                return 0;
            let displayOrder = this.pictureList[0].displayOrder;
            this.pictureList.forEach(p => {
                if(p.displayOrder > displayOrder){
                    displayOrder = p.displayOrder
                }
            });
            return displayOrder
        },
        minDisplayOrder () {
            if(!this.model.pictureList)
                return 0;
            if(!this.pictureList.length)
                return 0;
            let displayOrder = this.model.pictureList[0].displayOrder;
            this.pictureList.forEach(p => {
                if(p.displayOrder < displayOrder){
                    displayOrder = p.displayOrder
                }
            });
            return displayOrder
        }
    },
    methods: {
        handleEdit () {
        return;
        },
        onSubmit() {
        // console.log('submit!');
        },

        swapElement(i1, i2) {
            const item1 = this.pictureList[i1];
            const displayOrder1 = item1.displayOrder
            // this.model.pictureList[i1] = this.model.pictureList[i2];
            // this.model.pictureList[i2] = item1
            item1.displayOrder = this.pictureList[i2].displayOrder
            this.pictureList[i2].displayOrder = displayOrder1

            this.$set(this.pictureList, i1, this.pictureList[i2])
            this.$set(this.pictureList, i2, item1)

            this.$emit('onSwap', [this.pictureList[i2], this.pictureList[i1]])

            return [this.pictureList[i2], this.pictureList[i1]]
        },
        async handleRemove(file) {
            console.log('要删除的图片为：',file);
            this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                console.log('图片列表：',this.pictureList);
                console.log('图片克隆列表：',this.pictureListModel);

                let productPictureId = 0
                let url = ''
                const isNew = file.response && file.response.code === 200
                if(file.response && file.response.url) {
                    url = file.response.url // {name: ..., raw: File, response: {}, uid: 111, url: "blob:http://localhost/39f4d519-ce81-493c-b3f4-5239281261a2" }
                } else {
                    url = file.url
                }
                console.log('url=', url);
                // 1、删除 file-list 中的图片
                const index = this.pictureList.findIndex( (p, i) => {
                    return p.url === url         
                })
                console.log('图片列表index：', index);
                if(index > -1){
                    productPictureId = this.pictureList[index].productPictureId
                    this.pictureList.splice(index, 1)   
                }
                // if(isNew){
                //     const pictureItem =  this.$refs.pictureItem
                //     console.log('pictureItem.parentNode:', pictureItem.parentNode);
                //     const ul = pictureItem.parentNode.parentNode;
                //     ul.removeChild(pictureItem.parentNode)// ul.lastChild
                // }
                // 2、删除 file-list 克隆数组 中的图片
                const index2 = this.pictureListModel.findIndex( (p, i) => {
                    return p.url === url          
                })
                console.log('图片克隆列表index：', index2);
                if(index2 > -1){    
                    productPictureId = this.pictureListModel[index2].productPictureId
                    this.pictureListModel.splice(index2, 1)
                }
                // 3、 执行服务器端的删除
                const res = await deleteProductPicture(productPictureId)
                this.$emit('onDelete', productPictureId)
                // console.log('当前图片：',this.$refs.pictureUploader.$el);
                // console.log('当前图片：', res);
                this.$message({type: 'success',message: '删除成功!'})
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                })     
            })
        },
        async handleMoveUp(picture) {  
            if(picture.displayOrder <=  this.minDisplayOrder ){
                this.msgError('已经是第一个了，不能再向上移动了！')
                return
            }
            const index = this.pictureList.findIndex( (p, i) => {
                return p.displayOrder === picture.displayOrder          
            })
            // const picture = await swapPictureDisplayOrder(postData)
            // console.log('index=',index);
            const pictures = this.swapElement(index - 1, index)
            
            const res = await updatePictures(pictures)
            console.log('updatePictures:', res)
        },
        async handleMoveDown(picture) {
            if(picture.displayOrder ===  this.maxDisplayOrder ){
                this.msgError('已经是最后一个了，不能再向下移动了！')
                return
            }
            const index = this.pictureList.findIndex( (p, i) => {
                return p.displayOrder === picture.displayOrder          
            })
            const pictures = this.swapElement(index, index + 1)
            const res = await updatePictures(pictures)
            console.log('updatePictures:', res)
        },
        handlePreview(file) {
            // console.log(file);
        },
        handleDownload(file) {
            // console.log(file);
        },
        async handleCover(file) {
            // console.log(file);
            // this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
            //     confirmButtonText: '确定',
            //     cancelButtonText: '取消',
            //     type: 'warning'
            // }).then(() => {
            //     this.$message({
            //         type: 'success',
            //         message: '删除成功!'
            //     })
            // }).catch(() => {
            //     this.$message({
            //         type: 'info',
            //         message: '已取消删除'
            //     })         
            // })

            

            try {
                const confirm = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                })
                console.log('aa:', confirm)
                if (confirm !== 'confirm')
                  return;
                // 执行逻辑写到这里

            } catch (e) {
                console.log('e=',e)
                this.$message({ type: 'info', message: '已取消删除'})  
            }
        },
        async onUploadSuccess(res, file, fileList) {
            if(res.code !== 200){
                this.$message.error(res.msg)
                return;
            }
            console.log('上传成功开始...', this.pictureList)
            const filename = res.picture.originalFilename
            if(!filename){
                return
            }
            const postData = {
                    mimeType:  res.picture.mimeType,
                    originalFilename: res.picture.originalFilename, 
                    // seoFilename: null, 
                    // altAttribute: null, 
                    // titleAttribute: null, 
                    virtualPath: res.picture.virtualPath, 
                    // size: 356013, 
                    productId: this.model.productId,
                    displayOrder: this.maxDisplayOrder + 1,
                    pictureType: 1
            }
            const picture = await addPicture(postData)
            console.log('上传的图片为：', picture)
            const pictureModel = {
                name: filename,
                url: res.url, // URL.createObjectURL(file.raw)
                pictureId: picture.pictureId,
                productPictureId: picture.productPictureId,
                productId: picture.productId,
                displayOrder: picture.displayOrder
            }
            this.$emit('onAdd', pictureModel)
            // 使用 push方法会造成 闪动
            // this.pictureList.push(pictureModel)
            // 这里 hack 一下，不知行不行
            const len = this.pictureList.length
            this.pictureList.length = len + 1
            this.pictureList[len] = pictureModel

            this.pictureListModel.push(pictureModel)
            console.log('pictureList=', this.pictureList) 
        },
        async loadPictures (productId) {
            const {data: productPictures} = await getProductPictures({productId: productId})
            // console.log('productPictures:', productPictures)
            // 这里将 获取图片放到 图片 tabItem 中
            this.pictureList = productPictures
            this.pictureListModel = productPictures.map((p, index) => {
                return {
                    name: p.name,
                    url: p.url, 
                    pictureId: p.pictureId,
                    productPictureId: p.productPictureId,
                    productId: p.productId,
                    displayOrder: p.displayOrder
                }
            })
        },
        beforeUpload(file) {
            // console.log('beforeUpload:', file)
            const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
            const isLt2M = file.size / 1024 / 1024 < 2;

            if (!isJPG) {
                this.$message.error('上传图片只能是 JPG / png 格式!');
            }
            if (!isLt2M) {
                this.$message.error('上传图片大小不能超过 2MB!');
            }
            return isJPG && isLt2M;
        }
    },
    mounted () {
        // console.log('product picture mounted')
        // 此时 this.model 还是个空对象， {__ob__: Observer, __proto__: Object}
        // console.log('product:', this.model)
        // console.log('pictureList:', this.pictureList)
        // this.pictureList = this.model.pictureList
    },
    created () {
        // console.log('created')
    }
}
</script>

<style scoped>
 /deep/ .el-upload-list__item-actions {
    display: flex;
    margin-left: 30px;
    width: 300px;
    height: 70px;
    line-height: 70px;

    align-items: center;
    justify-content: space-around;
 }
</style>